<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
require_once ('Entity/Skill_Videos_Entity.php');
class Skill_Videos_Model extends Skill_Videos_Entity
{
    public function __construct()
    {
        parent::__construct();
    }
    
    public function getVideo_byAlias($alias)
    {
        $sql = "SELECT v.id
            FROM skill_videos v
            WHERE v.alias = ? ";
        $query = $this->db->query($sql, array($alias));
        if ($query->num_rows() > 0) {
            return $query->row();
        }
        return array();
    }
    
    public function upHit($id = 0)
    {
        if (!isset($_SESSION['skill_videos'][$id])) {
            $_SESSION['skill_videos'][$id] = $id;
            $sql = "UPDATE skill_videos SET hit = hit + 1 WHERE id = $id";
            $this->db->query($sql);
        }
        
    }
    
    public function getVideo_byCategory($cid = 0, $vid = 0)
    {
        $sql = "SELECT v.id, v.title, c.title as ctitle, v.created,  v.alias, v.url_thumbnail
            FROM skill_videos v
            INNER JOIN skill_video_categories vc ON vc.vid = v.id
			INNER JOIN skill_categories c ON c.id = vc.cid 
			INNER JOIN skill_menus m ON c.mid = m.id
            WHERE  v.status = 1 AND c.id = ? ";
        if ($vid == 1) {
            $sql .= " AND v.id != $vid";
        }
        $sql .= "
            ORDER BY c.created DESC";
        $query = $this->db->query($sql, array($cid));
        return $query->result();
    }
    
    public function getVideo_ByMenu($mid = 0, $ofset = 0, $limit = 10, $hit = 0)
    {
        $sql = "SELECT v.id, v.title, v.url_thumbnail, v.created, v.alias, v.hit
                FROM skill_videos v
                INNER JOIN skill_video_categories vc ON vc.vid = v.id
    			INNER JOIN skill_categories c ON c.id = vc.cid 
    			INNER JOIN skill_menus m ON c.mid = m.id
            	WHERE m.id = $mid AND v.status = 1
                GROUP BY v.id    
                ";
        if ($hit == 1) {
            $sql .= " ORDER BY hit DESC";
        } elseif ($hit == 2) {
             $sql .= " ORDER BY v.created DESC ";
        }
        else {
            $sql .= " ORDER BY RAND() ";
        }
        $sql .= " LIMIT $ofset, $limit";
        $query = $this->db->query($sql);
        return $query->result();
    }
     public function getVideo_byId($id = 0) 
    {
        $sql = "SELECT v.*, c.title as ctitle, c.alias calias, 
                    m.title as mtitle, m.alias as malias, c.mid
			FROM skill_videos v 
			INNER JOIN skill_video_categories vc ON vc.vid = v.id
			INNER JOIN skill_categories c ON c.id = vc.cid 
			INNER JOIN skill_menus m ON c.mid = m.id
			WHERE v.status = 1 AND v.id = $id
			GROUP BY v.id";
        $query = $this->db->query($sql);
        if ($query->num_rows() > 0) {
            return $query->row();
        } else {
            return array();
        }
    }
    
    
    
    public function dataSort($field, $order)
    {
        $xOrder = $order == 'asc' ? 'desc' : 'asc';
        $img = $order == 'desc' ? '<img src=\'/data/admin/down.jpg\' />' : ' <img src=\'/data/admin/up.jpg\' />';
        $url = anchor('skill_videos/sort/' . $field . '/' . $xOrder, t($field) . $img);
        $_SESSION['sm_sort_skill_videos'] = array(
            'field' => $field,
            'order' => $order,
            'url' => $url);
    }

    public function dataIndex($target)
    {
        $numshow = 25;
        $this->db->select('skill_videos.id, skill_videos.title, skill_videos.changed, skill_videos.url_thumbnail, skill_videos.created, skill_videos.status, skill_videos.hit');
        $this->db->from('skill_videos');


        if ($this->session->userdata('sm_filter_skill_categories') && $this->session->userdata('sm_filter_skill_categories') != -1) {
            $this->db->join('skill_video_categories', 'skill_video_categories.vid = skill_videos.id');
            $this->db->where('skill_video_categories.cid', $this->session->userdata('sm_filter_skill_categories'));
        }
            
        if ($this->session->userdata('sm_find_skill_videos')) {
            $this->db->like('skill_videos.title', $this->session->userdata('sm_find_skill_videos'));
        }
        if (isset($_SESSION['sm_sort_skill_videos'])) {
            $sort = $_SESSION['sm_sort_skill_videos'];
            $this->db->order_by('skill_videos.' . $sort['field'], $sort['order']);
        } else {
            $this->db->order_by('skill_videos.created', 'desc');
        }
        $this->db->limit($numshow, $target);
        $query = $this->db->get();
        $paging = paging_admin('skill_videos/index', $this->_total(), $numshow, 4);
        return array(
            'query' => $query,
            'paging' => $paging,
            'fil_skill_categories' => $this->Filter_skill_categories(),
            'formFind' => $this->formFind());
    }

    private function cbo_skill_categories($id = 0)
    {
        $this->load->helper("form");
        $sql = "SELECT * FROM skill_categories ORDER BY title ASC";
        $query = $this->db->query($sql);
        foreach ($query->result() as $row) {
            $options[$row->id] = $row->title;
        }
        //$sl = $id == 0 ? set_value("cid[]") : $id;
        if ($id != 0) {
            $this->load->model('Skill_Video_Categories_Model');
            $vcModel = new Skill_Video_Categories_Model();
            $arr = $vcModel->arrCid($id);
            $sl = $arr;
        } else {
            $sl = '';
        }
        
        
        $style = 'style="width: 500px; height: 130px;"';
        return form_multiselect("cid[]", $options, $sl, $style);
    }

    private function _total()
    {
        return $this->db->count_all_results("skill_videos");
    }

    private function _checkskill_videosById($id)
    {
        $query = $this->db->get_where("skill_videos", array("id" => $id));
        if ($query->num_rows() > 0)
            return true;
        else {
            notify_set_messages(notify_atten(t("Record không tồn tại")), "skill_videos");
            return false;
        }
    }

    private function formFind()
    {
        $this->load->helper('form');
        $attributes = array('name' => 'frmFind', 'id' => 'frmFind');
        $f = form_open(site_url('skill_videos/find'), $attributes);
        $data = array(
            'name' => 'txt_find',
            'id' => 'txt_find',
            'value' => '',
            'style' => 'width:200px');
        $f .= form_input($data);
        $s = array(
            'name' => 'submit',
            'value' => t('Find'),
            'class' => 'ibutton green',
            'style' => 'margin-left:10px');
        $f .= form_submit($s);
        if ($this->session->userdata('sm_find_skill_videos')) {
            $r = array(
                'name' => 'btnReset',
                'value' => 'Reset',
                'class' => 'ibutton red',
                'style' => 'margin-left:10px');
            $f .= form_submit($r);
        }
        $f .= form_close();
        return $f;
    }

    private function Filter_skill_categories()
    {
        $this->load->helper('form');
        $query = $this->db->get('skill_categories');
        $options['-1'] = 'Tất cả'; 
        foreach ($query->result() as $row) {
            $options[$row->id] = $row->title;
        }
        $id = !$this->session->userdata('sm_filter_skill_categories') ? 0 : $this->session->userdata('sm_filter_skill_categories');
        $attributes = array('name' => 'frmFilterskill_categories', 'id' => 'frmFilterskill_categories');
        $f = form_open(site_url('skill_videos/filterskill_categories'), $attributes);
        $f .= form_dropdown('cid', $options, $id);
        $data = array(
            'name' => 'btnFilterskill_categories',
            'class' => 'ibutton green',
            'style' => 'margin-left:10px',
            'value' => t('Filter'));
        $f .= form_submit($data);
        if ($this->session->userdata('sm_filter_skill_categories')) {
            $r = array(
                'name' => 'btnReset',
                'class' => 'ibutton red',
                'style' => 'margin-left:10px',
                'value' => 'Reset');
            $f .= form_submit($r);
        }
        $f .= form_close();
        return $f;
    }


    public function dataEdit($id)
    {
        if (!$this->_checkskill_videosById($id))
            return redirect(site_url('skill_videos'));
        $this->load->helper('editor');
        $query = $this->db->get_where('skill_videos', array('id' => $id));
        return array(
            'query' => $query, 
            'cbo_skill_categories' => $this->cbo_skill_categories($id),
        );
    }

    public function dataAdd()
    {
        $this->load->helper('editor');
        return array('cbo_skill_categories' => $this->cbo_skill_categories());
    }

    public function checkForm()
    {
        $this->form_validation->set_rules('title', t('title'), 'trim|required');
        $this->form_validation->set_rules('contents', t('contents'), 'trim|required');
        $this->form_validation->set_rules('url_thumbnail', t('url_thumbnail'), 'trim|required');
        $this->form_validation->set_rules('url_video', t('url_video'), 'trim|required');
        $this->form_validation->set_rules('cid[]', t('cid'), 'trim|required|integer');
        return $this->form_validation->run();
    }

    public function doUpdate()
    {
        $this->load->model('Skill_Video_Categories_Model');
        $vcModel = new Skill_Video_Categories_Model();
        
        $this->load->helper('text');
        $title = $this->input->post('title');
        $this->setTitle($title);
        $time = strtotime($this->input->post('created'));
        $this->setAlias(iurl_title($title).'-'.date('y-m-d', $time));
        $this->setCreated($time);
        $this->setContents($this->input->post('contents'));
        $this->setUrl_thumbnail($this->input->post('url_thumbnail'));
        $this->setUrl_video($this->input->post('url_video'));
        $this->setStatus($this->input->post('status'));
        
        $arrCid = $this->input->post('cid');
        if (isset($_POST['idx'])) {
            $id = decrypt($_POST['idx']);
            $this->setId($id);
            $this->setChanged(time());
            $vcModel->update($id, $arrCid);
            $this->save();
            return true;
        } else {
            $id = $this->save();
            $vcModel->saveVC($id, $arrCid);
            return true;
        }
    }
}
